package com.choupin.choupin.admin.service.impl;

import com.choupin.choupin.admin.entity.UpdateResult;
import com.choupin.choupin.admin.entity.User;
import com.choupin.choupin.admin.mapper.ManageLotteryMapper;
import com.choupin.choupin.admin.mapper.ManageUserMapper;
import com.choupin.choupin.admin.service.IManageUser;
import com.choupin.choupin.entity.Member;
import com.choupin.choupin.mapper.MemberMapper;
import com.choupin.choupin.mapper.UserMapper;
import com.choupin.choupin.service.exception.ParameterIsEmptyException;
import com.choupin.choupin.service.exception.SelectExcepion;
import com.choupin.choupin.service.exception.UpdateException;
import com.choupin.choupin.utils.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("ALL")
@Service
public class ManageUserImpl implements IManageUser {

    @Autowired
    ManageUserMapper manageUserMapper;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    ManageLotteryMapper manageLotteryMapper;

     @Autowired
    UserMapper userMapper;

     @Autowired
     RedisUtils redisUtils;

    @Override
    public List<User> showUser(Integer currentPage, Integer pagePize) {
//       所有用户信息
        List<com.choupin.choupin.entity.User> users=manageUserMapper.selectAllUser(currentPage,pagePize);
        if (users==null||users.size()<=0){
            throw new SelectExcepion("查询用户表错误！");
        }
        System.out.println("查询出的用户"+users);
        List<User> userList=new ArrayList<>();
//        遍历用户
        for (com.choupin.choupin.entity.User u:users){
            User adUser=new User();
//            查看会员类型
          if(u.getIsVip()==1){
              Member member=memberMapper.selectMemberUserOneId(u.getMemberId());
              if (member==null){
                  throw new SelectExcepion("查询会员表异常");
              }
              adUser.setIcon(member.getIcon());
          }else {
              adUser.setIcon(null);
          }
//          查询用户的奖品数
             Integer prizeCount=manageLotteryMapper.prizeCount(u.getPhone());
             adUser.setPrizeCount(prizeCount);
            adUser.setId(u.getId());
            adUser.setPhone(u.getPhone());
            adUser.setNickname(u.getNickname());
            adUser.setWeight(u.getWeight());
            userList.add(adUser);
        }
        System.out.println("查询数据成功！"+userList);
        return userList;
    }

    @Override
    public List<User> selectUsers(String id, String phone, String nickname, Integer currentPage, Integer pagePize) {
//        参数检测
        if (currentPage==null||pagePize==null){
            throw new ParameterIsEmptyException("参数为空！");
        }
//        判断id是否为空
        List<com.choupin.choupin.entity.User> users=new ArrayList<>();
        if (id!=null&&id!=""){
            users=manageUserMapper.selectUsers(Integer.parseInt(id),id,phone,nickname,currentPage,pagePize);
        }else {
            users=manageUserMapper.selectUsers(0,id,phone,nickname,currentPage,pagePize);
        }
//        调用数据库查询
        System.out.println("联合查询查到的数据："+users);
       List<User> userList=new ArrayList<>();
       //        遍历用户
        for (com.choupin.choupin.entity.User u:users){
            User adUser=new User();
//            查看会员类型
            if(u.getIsVip()==1){
                Member member=memberMapper.selectMemberUserOneId(u.getMemberId());
                if (member==null){
                    throw new SelectExcepion("查询会员表异常");
                }
                adUser.setIcon(member.getIcon());
            }else {
                adUser.setIcon(null);
            }
//          查询用户的奖品数
            Integer prizeCount=manageLotteryMapper.prizeCount(u.getPhone());
            adUser.setPrizeCount(prizeCount);
            adUser.setId(u.getId());
            adUser.setPhone(u.getPhone());
            adUser.setNickname(u.getNickname());
            adUser.setWeight(u.getWeight());
            userList.add(adUser);
        }
        System.out.println("查询数据成功！"+userList);
        return userList;
    }

    @Override
    public UpdateResult showUpdate(String phone) {
//        参数校验
        if (phone==null){
            throw new ParameterIsEmptyException("参数为空！");
        }
        com.choupin.choupin.entity.User user=manageUserMapper.selectUsersToPhone(phone);
        UpdateResult updateResult=new UpdateResult();
        if (user==null){
            throw new SelectExcepion("查询错误！");
        }
        updateResult.setMemberStatus(user.getIsVip());
        if (user.getIsVip()==1){
            updateResult.setMemberStatus(user.getMemberId());
        }
        updateResult.setId(user.getId());
        updateResult.setPhone(user.getPhone());
        updateResult.setNickname(user.getNickname());
        updateResult.setIsDelete(user.getIsDelete());
        LocalDateTime endTime=null;
//        判断redis中的封号时间
        if (RedisUtils.getCommonValue("seal_"+phone)!=null)   {
        String  endTimeStr=RedisUtils.getValue("seal_"+phone);
            //        时间转换
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            System.out.println("从redis中取出的封号时间是："+endTimeStr);
        endTime=LocalDateTime.parse(endTimeStr.replace("T"," "),formatter);

        }
        updateResult.setEndTime(endTime);
        updateResult.setWeight(user.getWeight());
        System.out.println("查询更新数据成功！"+updateResult);
        return updateResult;
    }

    @Override
    public UpdateResult update(UpdateResult updateResult) {
         String isDeleteStr=null;
         String weightStr=null;
          String memberIdStr=null;
          Integer isVip=0;
//          查询用户信息
        com.choupin.choupin.entity.User user=manageUserMapper.selectUsersToPhone(updateResult.getPhone());
        if (user==null){
            throw new SelectExcepion("查询用户不存在！");
        }
//        与原来不想等的数据都要更新
//        封号状态
        if (updateResult.getIsDelete()!=user.getIsDelete()){
            isDeleteStr="true";
            System.out.println("修改账号状态");
            if (updateResult.getIsDelete()==1){
                //        时间转换
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                if (RedisUtils.getCommonValue("seal_"+updateResult.getPhone())!=null){
                    LocalDateTime redisTime=LocalDateTime.parse(RedisUtils.getValue("seal_"+updateResult.getPhone()).replace("T"," "),formatter);
//                    修改了封号时间
                    if (!updateResult.getEndTime().equals(redisTime)){
//                 将封禁截止时间写入缓存
                        String endTime=updateResult.getEndTime().toString();
                        redisUtils.addRedis("seal_"+updateResult.getPhone(),endTime);
                        System.out.println("将封禁日期写入Redis缓存！");
                    }
                }else {
                    //                 将封禁截止时间写入缓存
                    String endTime=updateResult.getEndTime().toString();
                    redisUtils.addRedis("seal_"+updateResult.getPhone(),endTime);
                    System.out.println("将封禁日期写入Redis缓存！");
                }


            }
        }

//          中奖概率
          if (updateResult.getWeight()!=user.getWeight()){
              weightStr="ture";
          }
//          会员类型
//            转换回普通类型
              if(updateResult.getMemberStatus()!=user.getMemberId()&&updateResult.getMemberStatus()==0){
                 isVip=0;
                 memberIdStr="true";
              }
//              修改成其它会员类型
              if (updateResult.getMemberStatus()!=user.getMemberId()&&updateResult.getMemberStatus()!=0){
                  isVip=1;
                  memberIdStr="true";
              }
//              修改用户信息
            Integer result=manageUserMapper.update(updateResult.getPhone(),updateResult.getIsDelete(),isDeleteStr,updateResult.getWeight(),weightStr,updateResult.getMemberStatus(),memberIdStr,isVip);
            if (result!=1||result==null){
                throw new UpdateException("修改用户信息失败");
            }
        System.out.println("修改用户信息成功！");
            return updateResult;
    }
}
